#include "groupmodel.hpp"
#include "database.hpp"

bool GroupModel::CreateGroup(Group& group)
{
    char sql[1024] = {0};
    sprintf(sql, "insert into allgroup(groupname, groupdesc) values('%s', '%s')", \
            group.GetName().c_str(), group.GetDesc().c_str());
    MySQL mysql;
    if (mysql.Connect()) {
        if (mysql.Update(sql)) {
            group.SetId(mysql_insert_id(mysql.GetConnection()));
            return true;
        }
    }
    return false;
}

void GroupModel::AddGroup(int userid, int groupid, const std::string& role)
{
    char sql[1024] = {0};
    sprintf(sql, "insert into groupuser values(%d, %d, '%s')", groupid, userid, role.c_str());
    MySQL mysql;
    if (mysql.Connect()) {
        mysql.Update(sql);
    }
}

std::vector<Group> GroupModel::QueryGroups(int userid)
{
    char sql[1024] = {0};
    sprintf(sql, "select a.id,a.groupname,a.groupdesc from allgroup a inner join \
            groupuser b on a.id = b.groupid where b.userid=%d", userid);
    std::vector<Group> groupVec;
    MySQL mysql;
    if (mysql.Connect()) {
        MYSQL_RES* res = mysql.Query(sql);
        if (res != nullptr) {
            MYSQL_ROW row;
            while ((row = mysql_fetch_row(res)) != nullptr) {
                Group group;
                group.SetId(atoi(row[0]));
                group.SetName(row[1]);
                group.SetDesc(row[2]);
                groupVec.push_back(group);
            }
            mysql_free_result(res);
        }
    }

    // 查询群组的用户信息
    for (Group &group : groupVec) {
        sprintf(sql, "select a.id, a.name,a.state,b.grouprole from user a \
        inner join groupuser b on b.userid = a.id where b.groupid=%d", group.GetId());
        MYSQL_RES* res = mysql.Query(sql);
        if (res != nullptr) {
            MYSQL_ROW row;
            while ((row = mysql_fetch_row(res)) != nullptr) {
                GroupUser user;
                user.SetId(atoi(row[0]));
                user.SetName(row[1]);
                user.SetState(row[2]);
                user.SetRole(row[3]);
                group.GetUsers().push_back(user);
            }
            mysql_free_result(res);
        }
    }
    return groupVec;
}

std::vector<int> GroupModel::QueryGroupUsers(int userid, int groupid)
{
    char sql[1024] = {0};
    sprintf(sql, "select userid from groupuser where groupid=%d and userid!=%d", groupid, userid);

    std::vector<int> idVec;
    MySQL mysql;
    if (mysql.Connect()) {
        MYSQL_RES* res = mysql.Query(sql);
        if (res != nullptr) {
            MYSQL_ROW row;
            while ((row = mysql_fetch_row(res)) != nullptr) {
                idVec.push_back(atoi(row[0]));
            }
        }
    }
    return idVec;
}
